package utils;

import java.io.*;
import java.net.URL;
import java.net.URLConnection;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Properties;

/**
 * @author Braycep
 * @date 2019/1/7 9:38
 */
public class URLUtil {
    private static final Properties property;

    static {
        InputStream in = URLUtil.class.getResourceAsStream("/config.properties");
        property = new Properties();
        try {
            property.load(in);
        } catch (IOException e) {
            System.out.println("加载配置文件失败");
        }
    }

    private static String getURL(String key) {
        if (key == null) {
            return null;
        } else {
            if (property == null) {
                return getDefaultURL();
            } else {
                String url = property.getProperty("url");
                String type = property.getProperty("type");
                String id = property.getProperty("id");
                return replace(url, type, id, key);
            }
        }
    }

    public static String getPassword(String key) throws Exception {
        String string;
        try {
            string = getConnectionContent(getURL(key));
            if (string.contains("html") || string.contains("div") || string.contains("抱歉")) {
                throw new Exception("获取密码失败");
            }
            String password = string.substring(string.lastIndexOf("[password]") + 10, string.lastIndexOf("[password]") + 14);
            serialize(key, password);
            return password;
        } catch (Exception e) {
            System.out.println("API 1：获取密码失败！");
            String str = getPasswordFromBackupURL(key);
            if (str != null && str.matches("\"\\w{4}\"")) {
                serialize(key, str.substring(1, 5));
                return str.substring(1, 5);
            }
            System.out.println("API 2：获取密码失败！");
            throw new Exception("获取密码失败");
        }
    }

    private static String getPasswordFromBackupURL(String key) throws Exception {
        String url = property.getProperty("url-backup");
        if (key == null || "".equals(key)) {
            return null;
        } else {
            url = url.replace("#{key}", key).replace("#{ver}", "web-client");
            String string = getConnectionContent(url);
            return string.substring(string.indexOf("\"access_code\":"), string.indexOf("\"access_code\":\"") + 6);
        }
    }

    private static String getConnectionContent(String url) throws Exception {
        URLConnection connection = new URL(url).openConnection();
        BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF8"));
        String line;
        StringBuilder sb = new StringBuilder();
        while ((line = br.readLine()) != null) {
            sb.append(line);
        }
        return sb.toString();
    }

    private static String replace(String url, String type, String id) {
        return url.replaceAll("#\\{type}", type).replaceAll("#\\{id}", id);
    }

    private static String replace(String url, String type, String id, String key) {
        String string = replace(url, type, id);
        return string.replace("#{key}", key);
    }

    private static String getDefaultURL() {
        String url = "http://api.yyyr.net/api?type=#{type}&id=#{id}&text=Getbaidupanpassword#{key}";
        String id = "root";
        String type = "Windows%2010";
        return replace(url, type, id);
    }

    private static void serialize(String key, String password) throws IOException {
        String path = property.getProperty("historyPath");
        File history = new File(path);
        if (!history.exists()) {
            if (!history.createNewFile()) {
                throw new IOException("创建文件失败");
            }
        }

        BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(history), "UTF8"));
        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(history, true), "UTF8"));

        String line;
        while ((line = br.readLine()) != null) {
            if (line.toUpperCase().contains(key.toUpperCase())) {
                bw.close();
                br.close();
                return;
            }
        }

        line = "==== Query " + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()) + " ====\r\n";
        String info = "Key: " + key + "\r\nPassword: " + password + "\r\n\r\n";
        bw.write(line);
        bw.write(info);
        br.close();
        bw.close();
    }

    public static String getRandomWord(int length) {
        StringBuilder word = new StringBuilder();
        for (int i = 0; i < length; i++) {
            int index = (int) (Math.random() * 2);
            if (index == 1) {
                word.append((char) ((int) (Math.random() * 26) + 65));
            } else {
                word.append((int) (Math.random() * 10));
            }
        }
        return word.toString();
    }
}
